#include "header.h"
const char *building_version=__VERSION_ID__;
void printHelp()
{
    cout << "Usage: getAvgSim -vh [-c configFile] DOC_NUM latent_feature_file sim_file" << endl;
}

void print_building_info(void)
{ 
    printf("Building version:\t%s\nBuilding time:\t\t%s %s\n", building_version, __DATE__, __TIME__);
}
ConfigFile g_config;
DBBase g_db;
double getAvgSim(const char* relatedFileName, vector< vector<float> > &matrix);

int main (int argc, char* argv[])
{
    //cout << argc << endl;
    const char *optstring = "hvc:";
    char configFile[MAX_FILE_NAME_LEN] = "";
    int optch = 0;
    int doc_num = 0;
    const char *featureFile, *relateFile;
    string simFun;
    while ((optch = getopt(argc, argv, optstring)) != -1) {
        switch (optch) {
            case 'c':
                strcpy(configFile, optarg);
                break;
            case 'h':
                printHelp();
                return 0;
            case 'v':
                print_building_info();
                return 0;
        }
    }
    if (strlen(configFile) < 1) {
        if (argc < 3) {
            printHelp();
            exit(1);
        }
        else {
            doc_num = atoi(argv[1]);
            featureFile = argv[2];
            relateFile = argv[3];
        }
    }
    else {
        g_config.load(configFile);
        doc_num = atoi(g_config.Value("section_1", "doc_num").c_str());
        featureFile = g_config.Value("section_1", "feature_file").c_str();
        relateFile = g_config.Value("section_1", "relateQuestion_file").c_str();
    }
   
    vector< vector<float> > features(doc_num+1); 
    //首先初始化变量，将每个文档的向量空间模型描述放入vector数组中
    int itemNum = loadLatentFeatures(features, featureFile);
    if (itemNum != doc_num) {
        cout << "输入的item数目和实际读取到的item数目不一致，请检查！" << endl;
        exit(1);
    }
    //针对每一个问题和他们的相关问题，计算相关度，然后将所有问题的相关度加起来，再除以总的相关问题数目，就可以得到
    //平均相关度
    double avgSim = getAvgSim(relateFile, features);
    cout << "Average Similarity: " << avgSim << endl;
    return 0;
}
double getAvgSim(const char* relatedFileName, vector< vector<float> > &matrix)
{
    char rateStr[2000];
    char* pch;
    std::ifstream from (relatedFileName);
    if (!from.is_open()) {
        cout << "can't open input file:" << relatedFileName << "!\n";
        exit(1);
    }   
    int itemId = 1, simNum = 0, relatedId;
    double totalSim = 0.0;
    while(from.getline(rateStr,2000)){
        if (strlen(rateStr) < 3)continue;
        pch = strtok (rateStr, " ");
        if (pch != NULL) {
            itemId = atoi(pch);
        }
        pch = strtok (NULL, ",");
        int i = 0;
        while (pch != NULL) {
            relatedId = atoi(pch);
            //this->relates[itemId].push_back(relatedId);
            totalSim += getCosine(matrix[itemId], matrix[relatedId], 0, FEATURE_NUM-1);
            ++simNum;
            ++i;
            if(i >= NEIGHB_NUM) break;
            pch = strtok (NULL, ",");
        }
    }
    return totalSim/simNum;
}
